package com.example.book_springboot.controller;

import com.example.book_springboot.pojo.Book;
import com.example.book_springboot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;
import java.io.IOException;

@Controller
public class BookController {

    //依赖注入
    @Autowired
    BookService bookService;

    @RequestMapping("/index")
    public String index(HttpSession session){
        List<Book> bookLostAll = bookService.findGetBookLostAll();
        session.setAttribute("bookLostAll",bookLostAll);
        return "index";
    }

    @RequestMapping(value = "/search",method = RequestMethod.POST)
    public String search(String bookName,HttpSession session) throws IOException {
        List<Book> list = bookService.findGetBookByBookName(bookName);
        session.setAttribute("bookLostAll",list);
        return "index";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(Book book, HttpServletResponse repose)throws IOException{
        PrintWriter out = repose.getWriter();
        int count = bookService.findAddBook(book);
        if(count>=1){
            return "redirect:index";
        }
        return "add";
    }

    @RequestMapping("/addPage")
    public String addPage(){
        return "add";
    }

    @RequestMapping(value = "/ajaxDel",method = RequestMethod.POST)
    @ResponseBody
    public void ajaxDel(HttpServletResponse response,String id) throws IOException{
        System.out.println("删除id==========----------"+id);
        PrintWriter out = response.getWriter();
        Integer count = bookService.findDelBook(Integer.parseInt(id));
        System.out.println("删除状态=========----------"+id);
        boolean falg = false;
        if(count==1){
            falg=true;
        }
        out.print(falg);
    }

    @RequestMapping(value = "/updateGetBook")
    public String updateGetBook(String bookId,HttpSession session) throws IOException{
        Book book = bookService.findGetBookById(bookId);
        session.setAttribute("book",book);
        return "update";
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public String update(Book book,HttpServletResponse response) throws IOException{
        int count = bookService.findUpdateBook(book);
        if (count>=1){
            return "redirect:index";
        }
        return "update";
    }


}
